//剩余字数统计
var statInputNum = function(id){
	var curLength, numItem, max;
	var inputObj = $("#"+id);
	curLength = inputObj.val().length;
	numItem = inputObj.next().find("em");
	numItem.text(curLength);
	inputObj.on('input propertychange', function () {
		numItem.text(inputObj.val().length);
	});
};

$.fn.formSubmit = function(options){
	var defaults = {
		loadHtml:"正在保存数据",
		form:"",
		callback : "",
		callbefore :"",
		ajaxFun:""
	};
	var opts = $.extend(defaults, options);
	$(opts.form+" :text,"+opts.form+" :password").focus(function(){
		var v = $(this).val();
		if (v == '' && !$(this).is('.form-error')){
		}
		$(this).parent().parent().addClass("form-focus");
	}).blur(function(){
		$(this).valid();
	});
	$(opts.form+" select").change(function(){
		$(this).valid();
	});
	$(opts.form+" .ui-calendar").select(function(){
		$(this).valid();
	});
	this.bind("click", function(){
		if(opts.callbefore != "" && $.isFunction(opts.callbefore)) {
			opts.callbefore(this);
		};
		if ($(opts.form).valid()){
			if(opts.ajaxFun != "" && $.isFunction(opts.ajaxFun) ){
				$(this).hide();
				$("<span class='loadFormSubmit'><span><em>"+opts.loadHtml+"</em></span></span>").insertAfter(this);
				opts.ajaxFun(this);
				return false;
			}else  if(opts.callback != "" && $.isFunction(opts.callback)) {
				opts.callback(this);
				return false;
			}else{
				if($(this).attr("type")!="submit"){
					
					$(this).hide();
					$("<span class='loadFormSubmit'><span><em>"+opts.loadHtml+"</em></span></span>").insertAfter(this);

					setTimeout(function(){
						$(opts.form).submit();
					},0);
				}else{
					layer.load(2);
					// $(this).hide();
					// $("<span class='loadFormSubmit'><span><em>"+opts.loadHtml+"</em></span></span>").insertAfter(this);
				}
			}
		}

	});
};

$.fn.textSum = function() {
	this.css({
		"position": "relative"
	});
	this.each(function() {
		var inputMaxlength = $(this).find("input,textarea").attr("maxlength");
		$(this).append('<div class="sumtips" style="position:absolute; width:70px; height:30px; line-height:30px; text-align:right; font-size:12px; color:#999; padding-right:15px; right:0; bottom:0;">' + inputMaxlength + "/" + inputMaxlength + "</div>");
		if (inputMaxlength == undefined || inputMaxlength == "undefined") {
			$(this).children("input,textarea").attr("maxlength", "10");
			$(this).children(".sumtips").html($(this).find("input,textarea").attr("maxlength") + "/" + $(this).find("input,textarea").attr("maxlength"))
		}
		if ($(this).children("input").length > 0) {
			var oH = $(this).height();
			$(this).children("input").css({
				"paddingRight": "70px"
			}).siblings(".sumtips").css({
				"height": oH + "px",
				"line-height": oH + "px"
			})
		}
		if ($(this).children("textarea").length > 0) {
			$(this).children("textarea").css({
				"paddingBottom": "30px"
			}).siblings(".sumtips").css({
				"bottom": "8px"
			})
		}
	});
	this.on("keyup", "input,textarea", function() {
		var newSum = $(this).attr("maxlength") - $(this).val().length;
		$(this).siblings(".sumtips").html(newSum + "/" + $(this).attr("maxlength"))
	});

}

//编辑器
var editor= function (){
	$('.mod-txtArea').xheditor({
		html5Upload:false,
		//upMultiple:'1',
		//tools:'mini',
		tools:'Fontface,FontSize,Bold,Italic,Underline,Strikethrough,FontColor,BackColor,SelectAll,Removeformat,Align,List,Outdent,Indent,Link,Unlink,Table,Preview,Fullscreen',
		//skin:'nostyle',
		showBlocktag:false,
		internalScript:false,
		internalStyle:false,
		width:"100%",
		height:120,
		fullscreen:false,
		sourceMode:false,
		forcePtag:false,
		upImgUrl:"hmoGroupUpLogoFile.action",
		upImgExt:"jpg,jpeg,gif,png"
	});
};

$(function(){
	// 禁用页面的回车键功能
	// document.onkeydown = function(e) {
	// 	var e = e || event;
	// 	if(e.keyCode == 13) {
	// 		return false;
	// 	}
	// }
	
	htm.init();
	
	if (isMultiTab) {
		lastPageUrlCache = storage.getPageUrlCache();
		storage.setPageUrlCache();
	}
});

var storage = {
	setPageUrlCache : function(url) {
		var iframeId = $(".tabs-tab-content .tab-pane.active", parent.document).attr("id");
		if (!iframeId) return;
		
		if (typeof url == "undefined") {
			url = storage.getWindowUrl();
		}
		
		var cache = [];
		cache.push(url);
		if (lastPageUrlCache) {
			cache.push(lastPageUrlCache);
		}
		sessionStorage.setItem(iframeId + '_PageUrlCache', JSON.stringify(cache));
	},
	getPageUrlCache : function() {
		var iframeId = $(".tabs-tab-content .tab-pane.active", parent.document).attr("id");
		if (!iframeId) return "";
		
		var str = sessionStorage.getItem(iframeId + '_PageUrlCache');
		if (str) {
			var cache = JSON.parse(str);
			if (cache.length == 2) {
				var url = storage.getWindowUrl();
				if (url == cache[0]) {
					return cache[1];
				}
			}
			return cache[0];
		}
		return "";
	},
	deletePageUrlCache : function() {
		var iframeId = $(".tabs-tab-content .tab-pane.active", parent.document).attr("id");
		if (!iframeId) return "";
		return sessionStorage.removeItem(iframeId + '_PageUrlCache');
	},
	getWindowUrl : function() {
		var url = window.location.href;
		
		if ($("#pageListForm").size() > 0) {
			var url = $("#pageListForm").attr("action");
			if (!url.startsWith("/")) {
				url = window.location.pathname.substring(0, window.location.pathname.lastIndexOf("/") + 1) + url;
			}
			url = url + (url.indexOf("?") >=0 ? "&" : "?") + $("#pageListForm").serialize();
		}
		return url;
	}
}

var htm = {
	// 根据radios选择，显示隐藏区域
	radioVisible : function(radioName, visibleBox, showValue, dataValue) {
		showValue = Array.isArray(showValue) ? showValue : [showValue];
		
		$("input[type='radio'][name='"+radioName+"']").click(function() {
			if (showValue.contains($(this).val())) {
				visibleBox.removeClass("hidden").show();
			} else {
				visibleBox.addClass("hidden").hide();
			}
		});
		
		if (dataValue) {
			if (showValue.contains(dataValue)) {
				visibleBox.removeClass("hidden").show();
			} else {
				visibleBox.addClass("hidden").hide();
			}
		}
	},
	// ajax 加载select的option
	ajaxOption : function($o, url) {
		var dataVal = $o.attr("data-val");
		var dataKey = $o.attr("data-key");
		var dataName = $o.attr("data-name");
		dataKey = dataKey ? dataKey : "id";
		dataName = dataName ? dataName : "name";

		ajax.getData(url, {}, function(data) {
			var str = "";
			for (var i=0; i<data.length; i++) {
				str += '<option value="'+data[i][dataKey]+'">'+data[i][dataName]+'</option>';
			}

			$o.find("option[value!='']").remove();
			$o.append(str);
			if (dataVal) {
				$o.find("option[value='"+dataVal+"']").attr("selected", true);
			}

			if ($o.hasClass("view-model")) {
				$o.hide();
				if ($o.find("option:selected").val() != "") {
					$o.after($o.find("option:selected").text());
				}
			}
		});
	},
	// html 初始化
	init : function() {
		// 全选事件
		if($("#chkAll").length>0){
			$("#chkAll").checkboxAll({chkName:"chkItem",chkClass:"chkTd",callback: function(str,len,strAcount,strHtml){
				if (str) {
					$("#chkedInfo").show();
				} else {
					$("#chkedInfo").hide();
				}
				// len 选中的程长度
				$("#chkLength").html(len);
				// 选中checkbox 的和值 默认是用,分隔
				$("#chkTotalVal").val(str);
			}});

			var chkAllPage=$("input[type=checkbox][name='chkAllPageData']").prop("checked");
			if(chkAllPage){
				$("input[type=checkbox][name='checkAll']").prop("disabled",true);
				$("input[type=checkbox][name='chkItem']").prop("disabled",true);
			}
			$("input[type=checkbox][name='chkAllPageData']").click(function(){
				var val = $(this).prop("checked");
				if (val) {
					$("input[type=checkbox][name='checkAll']").prop("disabled",true);
					$("input[type=checkbox][name='chkItem']").prop("disabled",true);
					$("#chkedInfo").show();
					$("#chkLength").html($(".page-total-info span").text());
				} else {
					$("input[type=checkbox][name='checkAll']").prop("disabled",false);
					$("input[type=checkbox][name='chkItem']").prop("disabled",false);
					
					var len = $("input[type=checkbox][name='chkItem']:checked").length;
					$("#chkLength").html(len);
					if (len > 0) {
						$("#chkedInfo").show();
					} else {
						$("#chkedInfo").hide();
					}
					
				}
			});
		}
		//textarea enter换行
        if ($("textarea").length > 0) {
            $("textarea").each(function(index) {
                $("textarea")[index].addEventListener('keydown',function(e){
                    if(e.keyCode!=13){
                        return;
                    }else{
                        e.returnValue = false;
                        e = $(this).val();
                        $(this).val(e + '\n');
                    }
                });

            });
		}
		if ($(".fixTable").length > 0) {
			$(".fixTable").each(function() {
				var right = $(this).attr("data-right") ? parseInt($(this).attr("data-right")) : 1;
				if (right > 0) {
					$(this).tableHeadFixer({
			            "head": false,
			            "right": right,
			            "z-index": 3
			        });
				} else {
					$(this).tableHeadFixer({
			            "head": false
			        });
				}
			});
			
		}

	    if ($(".select-multiple").length > 0) {
	        //初始化多选搜索
	        $(".select-multiple").each(function () {
	        	if ($(this).attr("data-input")) {
	        		$(this).change(function() {
	        			$("#" + $(this).attr("data-input")).val($(this).val());
	        		});
	        	}
	        	
	        	var placeholder = $(this).attr("placeholder");
				if (!placeholder) {
					placeholder = $(this).find("option").eq(0).text();
				}
				if ($(this).find("option").eq(0).attr("value") == "") {
					$(this).find("option").eq(0).remove();
				}
	            $(this).fSelect({"placeholder": "<span style='color:#999'>"+placeholder+"</span>"});
                //获取选中的值
                $(this).val();
                //初始化值
                var arr = $(this).attr("data-val");
                if(arr !=""){
                    arr = arr.split(',');
                    //第一步，先给select标签赋值
                    $(this).val(arr);
                    //第二步，给fs-optgroup下对应的option添加样式selected
                   $(this).siblings(".fs-dropdown").find(".fs-option").each(function () {
                        if(arr.indexOf($(this)['context']['dataset']['value']) != -1){
                            $(this).addClass("selected");
                        }
                    });
                    //第三步，重新加载下拉框，使得添加了selected样式的option处于被勾选状态
                    $(this).fSelect('reloadDropdownLabel');
                };
                
                if ($(this).parents(".search").length > 0) {
                	$(this).parent(".multiple").tooltip({
    		            trigger:'focus hover',
    		            placement: 'auto top',
    		            title:function (){
    		                return placeholder;
    		            }
    		        })
                }
	        });
	        
	    }
		// select选中效果
		if ($("select").length > 0) {
			$("select").each(function(){
				var dataVal = $(this).attr("data-val");
				if (dataVal) {
					$(this).find("option[value='"+dataVal+"']").attr("selected", true);
				}

				if ($(this).hasClass("view-model")) {
					$(this).hide();
					if ($(this).find("option:selected").val() != "") {
						$(this).after($(this).find("option:selected").text());
					}
				}
			});
		}

		if ($(".select2").length > 0) {
			$(".select2").each(function() {
				var placeholder = $(this).attr("placeholder");
				if (!placeholder) {
					placeholder = $(this).find("option").eq(0).text();
				}
				var width = $(this).attr("data-width");
				var box = $(this).select2({
					placeholder: placeholder,
					width: width ? width : '100%',
					allowClear: true,
//                    width: '100%'
				});
				
				select2Box($(this), box);
			});

			$(".search .select2").each(function() {
				var placeholder = $(this).attr("placeholder");
				if (!placeholder) {
					placeholder = $(this).find("option").eq(0).text();
				}
				$(this).siblings(".select2-container").tooltip({
		            trigger:'focus hover',
		            placement: 'auto top',
		            title:function (){
		                return placeholder;
		            }
		        })
			});
		}

		if ($(".search input").size() > 0) {
	        $('.search input').attr("autocomplete","off");
	        $('.search input').tooltip({
	            trigger:'focus hover',
	            placement: 'auto top',
	            title:function (){
	            	return $(this).attr("placeholder");
	            }
	        })
			//按下搜索
            $('.search input').on('keydown', function(e) {
                var key = e.which;
                if (key == 13) {
                    e.preventDefault();
                    $("#btn-search").click();
                }
            });
	    }

		if ($(".search select").size() > 0) {
	        $('.search select').tooltip({
	            trigger:'focus hover',
	            placement: 'auto top',
	            title:function (){
	            	return $(this).find("option").eq(0).text();
	            }
	        })
	    }

		$.datetimepicker.setLocale('ch');
		if ($(".time-picker").length>0) {
			$(".time-picker").each(function() {
				var $this = $(this);
				$this.datetimepicker({
					datepicker:false,
					format: $this.attr("data-format") ? $this.attr("data-format") : "H:i",
					step: 30,
					onShow: function() {
						if ($this.attr("data-end-id") || $this.attr("data-end")) {
							var endTime = $this.attr("data-end") ? $this.attr("data-end") : $('#' + $this.attr("data-end-id")).val();
							var d = new Date();
							var s = d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate()+" "+endTime;
							var nS=new Date(s);
							nS.setMinutes(nS.getMinutes());
							if(endTime!=""){
								$this.datetimepicker({
									maxTime:nS,
								});
							}
						}
						if ($this.attr("data-start-id") || $this.attr("data-start")) {
							var start = $this.attr("data-start") ? $this.attr("data-start") : $('#' + $this.attr("data-start-id")).val();
							var d = new Date();
							var s = d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate()+" "+start;
							var nS=new Date(s);
							nS.setMinutes(nS.getMinutes()+10);
							$this.datetimepicker({
								minTime:nS,
							});
						}
					}
				});
			});

		}

		if ($(".date-picker").length>0) {
			$('.date-picker').each(function() {
				var $this = $(this);
				var format = $this.attr("data-format") ? $this.attr("data-format") : "Y-m-d";
				$this.datetimepicker({
					format: format,
					timepicker: format.indexOf("H:i") >= 0,
					onShow: function() {
						if ($this.attr("data-end-id") || $this.attr("data-end")) {
							var end = $this.attr("data-end") ? $this.attr("data-end") : $("#" + $this.attr("data-end-id")).val();;
							if (end) {
								$this.datetimepicker({
									maxDate: end
								});
							}
						}
						if ($this.attr("data-start-id") || $this.attr("data-start")) {
							var start = $this.attr("data-start") ? $this.attr("data-start") : $("#" + $this.attr("data-start-id")).val();
							if (start) {
								$this.datetimepicker({
									minDate: start
								});
							}
						}
					}
				});
			});
		}

		// 图片查看
		if ($(".img-viewer").length > 0) {
			$(".img-viewer").viewer({
				"fullscreen" : false
			});
		}

		//查询
		if($("#btn-search").length>0){
			$("#btn-search").click(function() {
				$(this).html("查询中，请稍等");
				page.search();
			});
		}

		// 导出
		if ($("#btn-export, .btn-export").length>0) {
	        $("#btn-export, .btn-export").bind("click", function() {
	            var form = $("#pageListForm");
	            if (typeof $(this).attr("data-formId") != "undefined") {
	                form = $("#" + $(this).attr("formId"));
	            }
	            var exportUrl = $(this).attr("data-url");
	            exportUrl = exportUrl + (exportUrl.indexOf("?") >=0 ? "&" : "?") + form.serialize();

	            var exportFrm = document.createElement('form');
	            document.body.appendChild(exportFrm);
	            exportFrm.style.display = 'none';
	            exportFrm.action = exportUrl;
	            exportFrm.method = "post";
	            exportFrm.submit();
	            document.body.removeChild(exportFrm);
	        });
	    }
		
		if($(".input-amount").length>0){
			$(".input-amount").each(function(){
				input.amount(this);
			});
		}
		if($(".input-int").length>0){
			$(".input-int").each(function(){
				input.int(this);
			});
		}

		if (window["initMyHtml"]) {
			window["initMyHtml"]();
		}
	}

}

var ajax = {
	saveData : function(url, params, success) {
		if (typeof(isSubmitting) !== 'undefined' && isSubmitting) {
			return;
		}
		$.ajax({
	        type : "post",
	        cache : false,
	        timeout : 60000,
	        url : url,
	        data : JSON.stringify(params),
	        contentType : "application/json",
	        beforeSend: function (a, b, c) {
				load = layer.load(2);
				isSubmitting = true;
            },
	        success: function(data){
	            if (data.code == '0') {//返回成功处理自行编写
	            	if (data.msg && data.msg != '') {
	            		x.success(data.msg, function() {
		                	success(data.data);
		                	isSubmitting = false;
		                });
	            	} else {
	            		success(data.data);
	                	isSubmitting = false;
	            	}
	            }else{
	            	x.error(data.msg);
	            	isSubmitting = false;
	            }
	        }
		});
	},
	getData : function(url, params, success) {
		$.ajax({
	        type : "post",
	        cache : false,
	        timeout : 60000,
	        url : url,
	        data : params,
	        success: function(data){
	            if (data.code == '0') {//返回成功处理自行编写
	            	success(data.data);
	            }else{
	            	x.error(data.msg);
	            }
	        }
		});
	},
	getSyncData : function(url, params, success) {
		$.ajax({
	        type : "post",
	        cache : false,
	        timeout : 60000,
	        async : false,
	        url : url,
	        data : params,
	        success: function(data){
	            if (data.code == '0') {//返回成功处理自行编写
	            	success(data.data);
	            }else{
	            	x.error(data.msg);
	            }
	        }
		});
	},
	getDictMap : function(dictCode) {
		var dictMap = {};
		$.ajax({
	        type : "post",
	        cache : false,
	        async : false,
	        url : "/admin/sys/dict/value/ajaxMap?dictCode="+dictCode,
	        success: function(data){
	            if (data.code == '0') {//返回成功处理自行编写
	            	dictMap = data.data;
	            }else{
	            	x.error(data.msg);
	            }
	        }
		});
		return dictMap;
	}
}

var page = {
	search : function() {
		page.initNo();
		page.reload();
	},
	reload : function() {
		if ($("#pageListBox").size() > 0) {
			page.ajaxPage();
			return;
		} 
		if ($("#pageListForm").size() > 0) {
			layer.load(2);
			$("#pageListForm").submit();
			return;
		}
		location.reload();
	},
	initNo : function() {
		if($("#pageNumId").length>0){
			$("#pageNumId").val("1");
		}
	},
	ajaxPage : function() {
		$.ajax({
			type : "POST",
			url : $("#pageListBox").attr("data-url"),
			data : $("#pageListForm").serialize(),
			dataType : 'html',
			beforeSend: function (a, b, c) {
				  load = layer.load(2);
            },
			success : function(data, status) {
				layer.close(load);
				$("#pageListBox").html(data);
				$("#btn-search").html("查询");
				htm.init();
			},
			error : function() {
				x.error("当前操作失败.");
			}
		});
	}
}

var frm = {
	/**
	 * 提交表单
	 */
	submit : function(pageType, formId, formUrl, rules, fn) {
		rules = rules ? rules : {};
		formUrl = (formUrl && formUrl != "") ? formUrl : $("#"+formId).attr("action");
		$("#"+formId).validate({
			ignore: ':hidden',
			rules: rules,
			submitHandler: function(form) {
				if (typeof(isSubmitting) !== 'undefined' && isSubmitting) {
					return;
				}
				var options = {
					type : "post",
					url : formUrl,
					dataType:'json',
					timeout : 60000,
				  	beforeSubmit:function(a,b,c){
				  		load = layer.load(2, {time:60000});	
				  		isSubmitting = true;
				  	},								
					success : function(data) {
						layer.close(load);
						if (data.code == '0') {
							x.success(data.msg, function () {
                            	if (fn && $.isFunction(fn)) {
                            		fn(data);
                            	} else {
                            		if (pageType == 'iframe') {
                            			parent.page.reload();
                            			parent.layer.closeAll('iframe');
                            		} else if (pageType == 'dialog') {
                            			page.reload();
             							layer.closeAll();
                            		} else if (pageType == 'self') {
                            			x.back(true);
                            		} else if (pageType == 'reload') {
										location.reload();
									}
                            	}
                            	isSubmitting = false;
    						});
						} else{
							x.error(data.msg, function () {
								if (fn && $.isFunction(fn)) {
									fn(data);
								}
								isSubmitting = false;
							});
						}
					}
				};
				
				var tips = $("#"+formId).attr("data-tips");
				if (tips && tips != "") {
					layer.confirm(tips,function(){
						$("#"+formId).ajaxSubmit(options);
					});
				} else {
					$("#"+formId).ajaxSubmit(options);
				}
				return false;
			 }
		});
	},
	submit4Parent : function(pageType, formId, formUrl, rules, fn) {
		formUrl = (formUrl && formUrl != "") ? formUrl : $("#"+formId).attr("action");
		formUrl += (formUrl.indexOf("?") > 0 ? "&" : "?") + new Date().getTime();

		var params = "";
        if (pageType == "iframe") {
        	params = parent.frm.getParams("pageListForm", document.getElementById("parentChkModel"));
        } else if (pageType == "dialog") {
            params = frm.getParams("pageListForm", document.getElementById("parentChkModel"));
        }
        
        formUrl += "&" + params;
        frm.submit(pageType, formId, formUrl, rules, fn);
	},
	getSearchParam : function(formId) {
		var params = "";
		if(formId){
			params = $("#"+formId).serialize();
		}else{
			params = $("#pageListForm").serialize();			
		}
		params += "&selectWay="+1;
		return params;
	},
	getCheckParam : function() {
		var params = "";
		if($("input[type=checkbox][name='chkItem']:checked").length >= 1){
			var ids="";
			$("input[type=checkbox][name='chkItem']:checked").each(function(){
				ids +=  $(this).attr("extval")+",";
			});
			ids=ids.substring(0, ids.lastIndexOf(","));
			params = "selectWay="+2+"&ids="+ids;
		}
		return params;
	},
	/**
	 * 校验是否选择对象，比如有没“勾选所有页”，或者选中列表中的数据
	 */
	getParams : function(formId, o){
		// 1：优先判断勾选所有页，2: 优先判断checkbox，3：只返回checkbox，4：只查询所有页，
		var chkModel = 1; // 判断是否勾选所有页
		if (typeof(o) != 'undefined' && typeof($(o).attr("data-chkModel")) != 'undefined') {
			chkModel = parseInt($(o).attr("data-chkModel"));
		}
		
		if (chkModel == 3) {
			return frm.getCheckParam(formId);
		}
		if (chkModel == 4) {
			return frm.getSearchParam(formId);
		}
		
		if (chkModel == 1) {
			var chkAllPage=$("input[type=checkbox][name='chkAllPageData']").prop("checked");
			if (chkAllPage) {
				return frm.getSearchParam(formId);
			} else {
				return frm.getCheckParam(formId);
			}
		}
		
		if (chkModel == 2) {
			if($("input[type=checkbox][name='chkItem']:checked").length >= 1){
				return frm.getCheckParam(formId);
			} else {
				return frm.getSearchParam(formId);
			}
		}
		return "";
	},
	/**
	 * 校验是否选择对象，比如有没“勾选所有页”，或者选中列表中的数据
	 */
	getParamForJson : function(formId){
		var chkAllPage=$("input[type=checkbox][name='chkAllPageData']").prop("checked");
		var ids="";
		var params = {};
		if(chkAllPage){
			if($("input[type=checkbox][name='chkItem']").length < 1){
				return params;
			}
			var array;
			if(formId){
				array = $("#"+formId).serializeArray();
			}else{
				array = $("#pageListForm").serializeArray();	
			}
			$(array).each(
				function() {
					if (params[this.name]) {
						if ($.isArray(params[this.name])) {
							params[this.name].push(this.value);
						} else {
							params[this.name] = [ params[this.name],
									this.value ];
						}
					} else {
						params[this.name] = this.value;
					}
			});
			params["selectWay"] = 1;
		} else{
			if($("input[type=checkbox][name='chkItem']:checked").length<1){
				return params;
			}else{
				$("input[type=checkbox][name='chkItem']:checked").each(function(){
					ids +=  $(this).attr("extval")+",";
				});
				ids=ids.substring(0, ids.lastIndexOf(","));
				params["selectWay"] = 2;
				params["ids"] = ids;
			}
		}
		return params;
	}
}

var tab = {
	del : function(o) {
		var url = $(o).attr("data-url");
		url += (url.indexOf("?") > 0 ? "&" : "?") + new Date().getTime();
		var tips = $(o).attr("data-tips");
		var func = $(o).attr("data-fn");
		
		var params = "";
		var dataId = $(o).attr("data-id");
		if(dataId) {
			params = "id=" + dataId;
		} else {
			params = frm.getParams("pageListForm", o);
		}
		if(params=="") {
			x.error('请至少选择一条记录',{time: 1500});
			return false;
		}
		layer.confirm(tips,function(){
			if (typeof(isSubmitting) !== 'undefined' && isSubmitting) {
				return;
			}
			$.ajax({
			  type: "post",
			  cache: false,
			  url: url,
			  data : params,
			  beforeSend: function (a, b, c) {
				  load = layer.load(2);
				  isSubmitting = true;
              },
			  success: function(data){
				layer.close(load);
				if (data.code == '0') {//返回成功处理自行编写
					x.success(data.msg, function() {
						if (typeof func != "undefined") {
							eval(func);
						} else {
							page.reload();
						}
						isSubmitting = false;
                    });
				} else{
					x.error(data.msg);
					isSubmitting = false;
				}
			  }
			});
		})
	},
	deal : function(o) {
		var url = $(o).attr("data-url");
		url += (url.indexOf("?") > 0 ? "&" : "?") + new Date().getTime();
		var tips = $(o).attr("data-tips");
		var func = $(o).attr("data-fn");
		
		var params = "";
		var dataId = $(o).attr("data-id");
		if(dataId) {
			params = "id=" + dataId;
		} else {
			params = frm.getParams("pageListForm", o);
		}
		if(params=="") {
			x.error('请至少选择一条记录');
			return false;
		}
		layer.confirm(tips,function(){
			if (typeof(isSubmitting) !== 'undefined' && isSubmitting) {
				return;
			}
			$.ajax({
			  type: "post",
			  cache: false,
			  url: url,
			  data : params,
			  beforeSend: function (a, b, c) {
				  load = layer.load(2);
				  isSubmitting = true;
              },
			  success: function(data){
				layer.close(load);
				if (data.code == '0') {//返回成功处理自行编写
					x.success(data.msg, function() {
						if (typeof func != "undefined") {
							eval(func);
						} else {
							page.reload();
						}
						isSubmitting = false;
                    });
				} else{
					x.error(data.msg);
					isSubmitting = false;
				}
			  }
			});
		})
	},
    dealDialog : function(o) { //用于处理列表上按钮点击后进行弹窗页面处理的场景
        var url = $(o).attr("data-url");
        url += (url.indexOf("?") > 0 ? "&" : "?") + new Date().getTime();
        var dataId = $(o).attr("data-id");
        if (dataId) {
        	url += "&id=" + dataId;
        } else {
        	var params = frm.getParams("pageListForm", o);
            if (params == "") {
            	x.error('请至少选择一条记录', {time: 1500});
                return false;
            } else {
            	url += "&" + params;
			}
        }
        $(o).attr("data-href", url);
        admin.dialog(o);
	},
	dealIframe : function(o) { //用于处理列表上按钮点击后进行弹窗页面处理的场景
        var url = $(o).attr("data-url");
        url += (url.indexOf("?") > 0 ? "&" : "?") + new Date().getTime();
        var dataId = $(o).attr("data-id");
        if (dataId) {
        	url += "&id=" + dataId;
        } else {
        	var params = frm.getParams("pageListForm", o);
            if (params == "") {
            	x.error('请至少选择一条记录', {time: 1500});
                return false;
            } else {
            	url += "&" + params;
			}
        }
        $(o).attr("data-href", url);
        admin.iframe(o);
	},
	updateState : function(o, state) {
		var url = $(o).attr("data-url");
		url += (url.indexOf("?") > 0 ? "&" : "?") + new Date().getTime();
		var tips = $(o).attr("data-tips");
		var func = $(o).attr("data-fn");
		
		var params = "";
		var dataId = $(o).attr("data-id");
		if(dataId) {
			params = "id=" + dataId;
		} else {
			params = frm.getParams("pageListForm", o);
		}
		if(params=="") {
			x.error('请至少选择一条记录',{time: 1500});
			return false;
		}
		layer.confirm(tips,function(){
			if (typeof(isSubmitting) !== 'undefined' && isSubmitting) {
				return;
			}
			$.ajax({
			  type: "post",
			  cache: false,
			  url: url + "&state=" + state,
			  data : params,
			  beforeSend: function (a, b, c) {
				  load = layer.load(2);
				  isSubmitting = true;
              },
			  success: function(data){
				layer.close(load);
				if (data.code == '0') {//返回成功处理自行编写
					x.success(data.msg, function() {
						if (typeof func != "undefined") {
							eval(func);
						} else {
							page.reload();
						}
						isSubmitting = false;
                    });
				} else{
					x.error(data.msg);
					isSubmitting = false;
				}
			  }
			});
		})
	},
	sort : function(o) {
		var datas = {};
		$(".data-sort").each(function() {
			if ($(this).val() != "") {
				datas[$(this).attr("data-id")] = $(this).val();
			}
		});

		ajax.saveData($(o).attr("data-url"), datas, function() {
			page.reload();
		});
	}
}


x.error = function(msg) {
	layer.msg(msg, { time: 2000 , skin:'layer-error'});
}

x.error = function(msg, fn) {
	layer.msg(msg,{time: 2000, skin:'layer-error'}, function() {
		if (fn && $.isFunction(fn)) {
			fn();
		}
	});
}

x.info = function(msg) {
	layer.msg(msg,{time: 1500, skin:'layer-success'});
}
x.success = function(msg, fn) {
	layer.msg(msg,{time: 1500, skin:'layer-success'}, function() {
		if (fn && $.isFunction(fn)) {
    		fn();
    	}
    });
}
x.back = function(refresh) {
	if (isMultiTab) {
		if (lastPageUrlCache && lastPageUrlCache != "") {
			location.href = lastPageUrlCache;
			return;
		}
	}
	
	if (refresh) {
		$.cookie('page_refresh', '1', {path: '/'});
	}
	history.go(-1);
}
x.replace = function(url) {
	if (isMultiTab) {
		if (lastPageUrlCache && lastPageUrlCache != "") {
			storage.setPageUrlCache(lastPageUrlCache);
		}
	}
	
	location.replace(url);
}

